﻿using CareerUp.Services.RabbitMqServices;
using CareerUp.Services.RabbitMqServices.Impl;
using Lycoris.RabbitMQ.Extensions;
using Lycoris.RabbitMQ.Extensions.Options;
using Microsoft.Extensions.DependencyInjection;
using Model.Const;
using Services.RabbitMqServices.Consumer;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Utils.Helper;

namespace Extensions.Extensions
{
    public static class RabbitMqSetUp
    {
        /// <summary>
        /// 注入mq
        /// </summary>
        /// <param name="service"></param>
        public static void AddRabbitMqSetUp(this IServiceCollection services)
        {
            var c = AppHelper.GetJsonValue("RabbitMQ:Connection");
            var u = AppHelper.GetJsonValue("RabbitMQ:UserName");
            var p = AppHelper.GetJsonValue("RabbitMQ:Password");

            var mqBuilder = services.AddRabbitMQExtensions(opt =>
            {
                // ip地址
                opt.Hosts = new string[] { c };
                // 端口号 不设置默认：5672
                opt.Port = 5672;
                // 账号
                opt.UserName = u;
                // 密码
                opt.Password = p;
                // 虚拟机 不设置默认为：/
                opt.VirtualHost = "/";
                //// 是否持久化 不设置默认：true
                //opt.Durable = true;
                //// 是否自动删除 不设置默认：false
                //opt.AutoDelete = false;
            });

            //生产者  接口、实现类模式
            mqBuilder.AddRabbitProducer<IRabbitProducerService, RabbitProducerService>(opt =>
            {
                // 保留发布者数 默认：5
                opt.InitializeCount = 5;
                // 交换机名称
                opt.Exchange = MqExChangeName.Search;
                // 交换机类型 延迟队列
                opt.Type = RabbitExchangeType.Fanout;
                // 延迟秒数
                opt.DelayTime = 5;
                // 路由队列
                opt.RouteQueues = new RouteQueue[]
                {
                    new RouteQueue()
                    {
                        Route = MqRoutingName.Search,
                        Queue = MqQueueName.Search
                    }
                };
            });

            //消费者
            mqBuilder.AddRabbitConsumer(opt =>
            {
                // 是否自动提交 默认：false
                opt.AutoAck = false;
                // 每次发送消息条数 默认：2
                opt.FetchCount = 2;
                // 交换机类型
                opt.Type = RabbitExchangeType.Fanout;
                // 路由队列
                opt.RouteQueues = new RouteQueue[]
                {
                    new RouteQueue()
                    {
                        Route = MqRoutingName.Search,
                        Queue = MqQueueName.Search
                    }
                };
                opt.AddListener<ArticleSearchConsumer>(MqExChangeName.Search, MqQueueName.Search);
            });
        }
    }
}
